package com.guobox.movies.view.activity;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.afollestad.materialdialogs.Theme;
import com.google.gson.Gson;
import com.guobox.movies.APP;
import com.guobox.movies.R;
import com.guobox.movies.constant.Constant;
import com.guobox.movies.entity.MovieEntity;
import com.guobox.movies.entity.MovieSort;
import com.guobox.movies.entity.MovieType;
import com.guobox.movies.entity.NasEntity;
import com.guobox.movies.nasManager.NasIpCallback;
import com.guobox.movies.present.MoviesListPresentImp;
import com.guobox.movies.utils.MetricsScreen;
import com.guobox.movies.utils.ShellUtils;
import com.guobox.movies.utils.httpsutils.DownloadUtil;
import com.guobox.movies.view.MovieActivityIf;
import com.guobox.movies.view.adapter.Radapter;
import com.guobox.movies.view.decoration.MovieListItemDecoration;
import com.guobox.movies.view.timer.CateSlideTimer;
import com.guobox.movies.view.timer.CateTitleTimer;
import com.guobox.movies.view.timer.MovieFocusTimer;
import com.guobox.movies.view.timer.NumTipTimer;
import com.guobox.movies.view.timer.TimerCallback;

import java.util.ArrayList;
import java.util.List;

public class TMovieListActivity extends BaseActivity implements MovieActivityIf
        , TimerCallback, NasIpCallback {

    private final float normal = 1;
    private final float large = 1.12f;
    private final int duringFocus = 300;
    private final int duringUnfocused = 400;
    private final int tbUnfocusedColor = Color.argb(255, 118, 118, 118);
    private final int tbFocusColor = Color.WHITE;
    private final int State_Movies = 0;
    private final int State_Cate = 1;
    private final int State_Sort = 2;
    private final int Movies2Cate = 1;
    private final int Cate2Movies = 2;
    private final int Cate2Sort = 3;
    private final int Sort2Cate = 4;
    private final int Sort2Movies = 5;
    private static final int col_num = 5;

    private boolean isBack = false;
    private int focusState = State_Cate;
    private RecyclerView mainRv;
    Context context = this;

    private volatile int moviePosition = 0;
    private volatile int catePosition = 0;
    private volatile int sortPosition = 0;
    private volatile int sumMoviesNum = 0;

    private CateTitleTimer cateTitleTimer;
    private CateSlideTimer cateSlideTimer;
    private NumTipTimer numTipTimer;
    private MovieFocusTimer movieFocusTimer;

    LinearLayout cateBarContainer;
    LinearLayout sortBarContainer;
    TextView movieNumTip;
    Radapter radapter;

    public List<MovieType> movieTypes = MovieType.getMovieTypes();
    public List<MovieSort> movieSort = MovieSort.getSorts();

    //present
    public MoviesListPresentImp moviesPresentImp;

    public List<MovieEntity> movieEntities = null;

    private final static String TAG = "movieListActivity";

    ProgressDialog progressDialog;
    AnimationSet showMovieAnimationSet;

//    NasManager nasManager;
//    MaterialDialog searchDialog;
//    MaterialDialog searchProgress;
//    Timer searchTimer = new Timer();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tmovie_list);
        initTimer();
        initView();
        moviesPresentImp = new MoviesListPresentImp(this);
        resetCateTimer(focusState);
        movies2Cate();
        checkNasConnection();
//        initTimer();
//        initView();
//        moviesPresentImp = new MoviesListPresentImp(this);
//        resetCateTimer(focusState);
//        movies2Cate();
//        nasManager = new NasManager(this);
//        nasManager.addNasIpCallback(this);
//        NasEntity nasEntity = nasManager.getNas();
//        if (nasEntity == null|| TextUtils.isEmpty(nasEntity.getNasIp())) {
//            // TODO: 2017/12/11 showDialog
//        } else {
//            moviesPresentImp.getMoviesRequest(0, "name",nasEntity.getNasIp());
//        }
//        moviesPresentImp.delApk();
//        moviesPresentImp.checkAppUpdate();
    }


    @Override
    public void initConnection(String ip) {
        if (!TextUtils.isEmpty(ip)) {
            moviesPresentImp.getMoviesRequest(catePosition, "name",ip);
        }
    }

    void initTimer() {
        cateTitleTimer = new CateTitleTimer(2000, this);
        cateSlideTimer = new CateSlideTimer(100, this);
        numTipTimer = new NumTipTimer(2000, this);
        movieFocusTimer = new MovieFocusTimer(100, this);
    }

    void initView() {
        searchProgress = new MaterialDialog.Builder(this)
                .title("搜索")
                .theme(Theme.DARK)
                .content("搜索中")
                .cancelable(false)
                .canceledOnTouchOutside(false)
                .progress(true, 0).build();
        mainRv = (RecyclerView) findViewById(R.id.rv_t_list);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 5);
        mainRv.setLayoutManager(gridLayoutManager);
        movieNumTip = (TextView) findViewById(R.id.tv_rownum);
        movieNumTip.setTypeface(APP.getTypeface());


        radapter = new Radapter(new ArrayList<MovieEntity>(), movieTypes.get(0).getTypeName(), this);
        radapter.setHeaderView(LayoutInflater.from(this).inflate(R.layout.header_movielist, null));
        mainRv.setAdapter(radapter);
        mainRv.addItemDecoration(new MovieListItemDecoration());
        mainRv.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_SETTLING) {
                    View currentView = recyclerView.findViewWithTag(moviePosition);
                    if (currentView != null) {
                        currentView.clearAnimation();
                    }
                }
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    showFocus();
                }
            }
        });
        cateBarContainer = (LinearLayout) findViewById(R.id.lyt_cate_bar);
        sortBarContainer = (LinearLayout) findViewById(R.id.lyt_sort_bar);

        movieNumTip.setText(moviePosition + "/" + sumMoviesNum);
        movieNumTip.setTag(true);
        for (MovieType m :
                movieTypes) {
            TextView typeText = new TextView(getApplication());
            typeText.setText(m.getTypeName());
            typeText.setTypeface(APP.getTypeface());
            typeText.setTextSize(MetricsScreen.px2sp(this, 40));
            typeText.setGravity(Gravity.CENTER);
            if (m.getTypeId() == 0) {
                typeText.setTextColor(tbFocusColor);
            } else {
                typeText.setTextColor(tbUnfocusedColor);
            }
            typeText.setShadowLayer(10f, 0, 5f, Color.argb(255, 94, 94, 94));
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT);
            layoutParams.leftMargin = 25;
            layoutParams.rightMargin = 25;
            typeText.setLayoutParams(layoutParams);
            cateBarContainer.addView(typeText);
        }
        for (MovieSort sort :
                movieSort) {
            ImageView imageView = new ImageView(getApplication());
            if (sort.getSortId() == 0) {
                imageView.setImageResource(sort.getSortResF());
            } else {
                imageView.setImageResource(sort.getSortResUf());
            }
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(90, 90);
            layoutParams.leftMargin = 25;
            layoutParams.rightMargin = 25;
            imageView.setLayoutParams(layoutParams);
            sortBarContainer.addView(imageView);

        }
        showTips();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        int animationState = setActivityState(keyCode);
        resetCateTimer(focusState);
        switch (animationState) {
            case Movies2Cate:
                hiddenFocus();
                movies2Cate();
                return true;
            case Cate2Movies:
                cate2Movies();
                return true;
            case Cate2Sort:
                cate2Sort();
                return true;
            case Sort2Cate:
                sort2Cate();
                cateSlideTimer.reset();
                return true;
        }

        switch (focusState) {
            case State_Cate:
                int cate = chooseCate(keyCode);
                if (cate != -1) {
                    cateSlideTimer.reset();
                    return true;
                }
                break;
            case State_Sort:
                chooseSort(keyCode);
                return true;
            case State_Movies:
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    super.onKeyDown(keyCode, event);
                }
                if (chooseMovie(keyCode) != -1) {
                    showTips();
                    return true;
                }
                break;
        }

        if (focusState == State_Movies) {
            if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER
                    || keyCode == KeyEvent.KEYCODE_ENTER
                    || keyCode == KeyEvent. KEYCODE_NUMPAD_ENTER) {
                Intent intent = new Intent(TMovieListActivity.this, MovieDetailActivity.class);
                Gson gson = new Gson();

                // TODO: 2017/12/26
                if (movieEntities != null && movieEntities.size() > 0) {
                    intent.putExtra(Constant.MOVIE_ITEM
                            , gson.toJson(movieEntities.get(moviePosition), MovieEntity.class));
                    startActivity(intent);
                }

            }
        }
        return true;
    }

    private int changeSortFocus(int code) {
        switch (code) {
            case 0:
                ImageView ivPreL = (ImageView) sortBarContainer.getChildAt(sortPosition + 1);
                ivPreL.setImageResource(movieSort.get(sortPosition + 1).getSortResUf());
                ImageView ivL = (ImageView) sortBarContainer.getChildAt(sortPosition);
                ivL.setImageResource(movieSort.get(sortPosition).getSortResF());
                break;
            case 1:
                ImageView ivPreR = (ImageView) sortBarContainer.getChildAt(sortPosition - 1);
                ivPreR.setImageResource(movieSort.get(sortPosition - 1).getSortResUf());
                ImageView ivR = (ImageView) sortBarContainer.getChildAt(sortPosition);
                ivR.setImageResource(movieSort.get(sortPosition).getSortResF());
                break;
        }
        return -1;
    }

    private int chooseSort(int keyCode) {
        if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
            if (sortPosition != 0) {
                sortPosition = sortPosition - 1;
                changeSortFocus(0);
                return 0;
            }
        } else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
            if (sortPosition != sortBarContainer.getChildCount() - 1) {
                sortPosition = sortPosition + 1;
                changeSortFocus(1);
                return 1;
            }
        }
        return -1;
    }

    private int chooseCate(int keyCode) {
        if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
            if (catePosition != 0) {
                catePosition = catePosition - 1;
                TextView textViewPreL = (TextView) cateBarContainer.getChildAt(catePosition + 1);
                textViewPreL.setTextColor(tbUnfocusedColor);
                TextView textViewL = (TextView) cateBarContainer.getChildAt(catePosition);
                textViewL.setTextColor(tbFocusColor);
                return catePosition;
            }
        } else if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
            if (catePosition != cateBarContainer.getChildCount() - 1) {
                catePosition = catePosition + 1;
                TextView textViewPreR = (TextView) cateBarContainer.getChildAt(catePosition - 1);
                textViewPreR.setTextColor(tbUnfocusedColor);
                TextView textViewR = (TextView) cateBarContainer.getChildAt(catePosition);
                textViewR.setTextColor(tbFocusColor);
                return catePosition;
            }
        }
        return -1;
    }

    private int chooseMovie(int keyCode) {
        if (sumMoviesNum == 0) {
            return -1;
        }

        switch (keyCode) {
            case KeyEvent.KEYCODE_DPAD_LEFT:
                if (moviePosition != 0) {
                    hiddenFocus();
                    moviePosition = moviePosition - 1;
                    if (moviePosition < col_num) {
                        mainRv.smoothScrollToPosition(0);
                    } else {
                        mainRv.smoothScrollToPosition(moviePosition + 1);
                    }
                    showFocus();
                    return moviePosition;
                }
                break;
            case KeyEvent.KEYCODE_DPAD_RIGHT:
                if (moviePosition != sumMoviesNum - 1) {
                    hiddenFocus();
                    moviePosition = moviePosition + 1;
                    mainRv.smoothScrollToPosition(moviePosition + 1);
                    showFocus();
                    return moviePosition;
                }
                break;
            case KeyEvent.KEYCODE_DPAD_UP:
                if (moviePosition != 0) {
                    if (moviePosition <col_num) {
                        hiddenFocus();
                        moviePosition = moviePosition - 1;
                        if (moviePosition == 0) {
                            mainRv.smoothScrollToPosition(0);
                        } else {
                            mainRv.smoothScrollToPosition(moviePosition + 1);
                        }
                        showFocus();
                        return moviePosition;
                    } else {
                        hiddenFocus();
                        moviePosition = moviePosition - col_num;
                        if (moviePosition < col_num) {
                            mainRv.smoothScrollToPosition(0);
                        } else {
                            mainRv.smoothScrollToPosition(moviePosition + 1);
                        }
                        showFocus();
                        return moviePosition;
                    }
                }
                break;
            case KeyEvent.KEYCODE_DPAD_DOWN:
                if (moviePosition != sumMoviesNum - 1) {
                    if (sumMoviesNum - moviePosition -1 < col_num) {
                        hiddenFocus();
                        moviePosition = moviePosition + 1;
                        mainRv.smoothScrollToPosition(moviePosition + 1);
                        showFocus();
                        return moviePosition;
                    } else {
                        hiddenFocus();
                        moviePosition = moviePosition + col_num;
                        mainRv.smoothScrollToPosition(moviePosition + 1);
                        showFocus();
                        return moviePosition;
                    }
                }
                break;
        }
        return -1;
    }

    private void resetCateTimer(int focusState) {
        if (focusState == State_Cate || focusState == State_Sort) {
            cateTitleTimer.reset();
        }
    }

    private int setActivityState(int keyCode) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_MENU:
                if (focusState == State_Movies) {
                    focusState = State_Cate;
                    return Movies2Cate;
                }
                break;
            case KeyEvent.KEYCODE_DPAD_UP:
                if (focusState == State_Cate) {
                    focusState = State_Sort;
                    return Cate2Sort;
                }
                break;
            case KeyEvent.KEYCODE_DPAD_DOWN:
                if (focusState == State_Sort) {
                    focusState = State_Cate;
                    return Sort2Cate;
                } else if (focusState == State_Cate) {
                    focusState = State_Movies;
                    return Cate2Movies;
                }
                break;
            case KeyEvent.KEYCODE_BACK:
                if (focusState == State_Sort) {
                    focusState = State_Cate;
                    return Sort2Cate;
                } else if (focusState == State_Cate) {
                    focusState = State_Movies;
                    return Cate2Movies;
                }
                break;
        }
        return -1;
    }

    private void cate2Movies() {
        AnimationSet animationSet = new AnimationSet(true);
        TranslateAnimation translateAnimation =
                new TranslateAnimation(0, 0, 0, -140);
        translateAnimation.setDuration(300);
        animationSet.addAnimation(translateAnimation);
        animationSet.setAnimationListener(new Animation.AnimationListener() {


            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {

            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        animationSet.setFillAfter(true);
        animationSet.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                showFocus();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        cateBarContainer.startAnimation(animationSet);
    }

    private void sort2Cate() {
        AnimationSet cateAnimationSet = new AnimationSet(true);
        AnimationSet sortAnimationSet = new AnimationSet(true);
        TranslateAnimation cateTransAnimation =
                new TranslateAnimation(0, 0, 140, 0);
        AlphaAnimation cateAlphaAnimation =
                new AlphaAnimation(0, 1);
        TranslateAnimation sortTransAnimation =
                new TranslateAnimation(0, 0, 0, -140);
        AlphaAnimation sortAlphaAnimation =
                new AlphaAnimation(1, 1);
        cateTransAnimation.setDuration(300);
        sortTransAnimation.setDuration(300);
        cateAlphaAnimation.setDuration(300);
        sortAlphaAnimation.setDuration(300);
        cateAnimationSet.addAnimation(cateTransAnimation);
        cateAnimationSet.addAnimation(cateAlphaAnimation);
        sortAnimationSet.addAnimation(sortTransAnimation);
        sortAnimationSet.addAnimation(sortAlphaAnimation);
        cateAnimationSet.setFillAfter(true);
        sortAnimationSet.setFillAfter(true);
        cateBarContainer.startAnimation(cateAnimationSet);
        sortBarContainer.startAnimation(sortAnimationSet);
    }

    private void cate2Sort() {
        AnimationSet cateAnimationSet = new AnimationSet(true);
        AnimationSet sortAnimationSet = new AnimationSet(true);
        TranslateAnimation cateTransAnimation =
                new TranslateAnimation(0, 0, 0, 140);
        AlphaAnimation cateAlphaAnimation =
                new AlphaAnimation(1, 0);
        TranslateAnimation sortTransAnimation =
                new TranslateAnimation(0, 0, -140, 0);
        AlphaAnimation sortAlphaAnimation =
                new AlphaAnimation(1, 1);
        cateTransAnimation.setDuration(300);
        sortTransAnimation.setDuration(300);
        cateAlphaAnimation.setDuration(300);
        sortAlphaAnimation.setDuration(300);
        cateAnimationSet.addAnimation(cateTransAnimation);
        cateAnimationSet.addAnimation(cateAlphaAnimation);
        sortAnimationSet.addAnimation(sortTransAnimation);
        sortAnimationSet.addAnimation(sortAlphaAnimation);
        cateAnimationSet.setFillAfter(true);
        sortAnimationSet.setFillAfter(true);
        cateBarContainer.startAnimation(cateAnimationSet);
        sortBarContainer.startAnimation(sortAnimationSet);

    }

    private void movies2Cate() {
        AnimationSet animationSet = new AnimationSet(true);
        TranslateAnimation translateAnimation =
                new TranslateAnimation(0, 0, -140, 0);
        translateAnimation.setDuration(400);
        translateAnimation.setFillAfter(true);
        animationSet.addAnimation(translateAnimation);
        animationSet.setFillAfter(true);
        cateBarContainer.startAnimation(animationSet);
    }

    private void sort2Movies() {
        sort2Cate();
        cate2Movies();
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        return super.onKeyUp(keyCode, event);
    }

    private void showTips() {
        numTipTimer.reset();
        if (sumMoviesNum == 0) {
            movieNumTip.setText("0/0");
        } else {
            movieNumTip.setText(moviePosition + 1 + "/" + sumMoviesNum);
        }

        if (!((Boolean) movieNumTip.getTag())) {
            AnimationSet animationSet = new AnimationSet(true);
            TranslateAnimation translateAnimation =
                    new TranslateAnimation(200, 0, 0, 0);
            translateAnimation.setDuration(200);
            animationSet.addAnimation(translateAnimation);
            movieNumTip.startAnimation(animationSet);
            movieNumTip.setTag(true);
        }
    }

    private void showFocus() {
        showMovieAnimationSet = new AnimationSet(true);
        ScaleAnimation showMovieScaleAnimation = new ScaleAnimation(
                normal,
                large,
                normal,
                large,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f
        );
        showMovieScaleAnimation.setDuration(300);
        showMovieAnimationSet.addAnimation(showMovieScaleAnimation);
        showMovieAnimationSet.setFillAfter(true);
        View currentView = mainRv.findViewWithTag(moviePosition);
        if (currentView != null) {
            currentView.startAnimation(showMovieAnimationSet);
            // TODO: 16/8/25
            final TextView movieNameTV = (TextView) currentView.findViewById(R.id.tv_t_movie_name);
            ObjectAnimator nameAnimator = ObjectAnimator.ofFloat(movieNameTV, "alpha", 1f);
            nameAnimator.setDuration(duringFocus);
            nameAnimator.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {

                }

                @Override
                public void onAnimationEnd(Animator animation) {
//                    movieNameTV.requestFocus();
                }

                @Override
                public void onAnimationCancel(Animator animation) {

                }

                @Override
                public void onAnimationRepeat(Animator animation) {

                }
            });
            nameAnimator.start();
            ImageView bg_iv = (ImageView) currentView.findViewById(R.id.iv_bg_focus);
            ObjectAnimator bgAnimator = ObjectAnimator.ofFloat(bg_iv, "alpha", 1f);
            bgAnimator.setDuration(duringFocus);
            bgAnimator.start();
        } else {
            movieFocusTimer.reset();
        }

    }

    private void hiddenFocus() {
        AnimationSet hidenAnimationSet = new AnimationSet(true);
        ScaleAnimation scaleAnimation = new ScaleAnimation(
                large,
                normal,
                large,
                normal,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f
        );
        scaleAnimation.setDuration(duringUnfocused);
        hidenAnimationSet.addAnimation(scaleAnimation);
        hidenAnimationSet.setFillAfter(true);
        View currentView = mainRv.findViewWithTag(moviePosition);
        if (currentView != null) {
            currentView.startAnimation(hidenAnimationSet);
            TextView movieNameTV = (TextView) currentView.findViewById(R.id.tv_t_movie_name);
            ObjectAnimator nameAnimator = ObjectAnimator.ofFloat(movieNameTV, "alpha", 0f);
            nameAnimator.setDuration(duringUnfocused);
            nameAnimator.start();
            ImageView bg_iv = (ImageView) currentView.findViewById(R.id.iv_bg_focus);
            ObjectAnimator bgAnimator = ObjectAnimator.ofFloat(bg_iv, "alpha", 0f);
            bgAnimator.setDuration(duringUnfocused);
            bgAnimator.start();
        }

    }

    @Override
    public void refreshView(List<MovieEntity> movieEntities, String moiveTypeName) {
        if (movieEntities == null) {
            super.showSearchAlert();
            return;
        }
        this.movieEntities = movieEntities;
        moviePosition = 0;
        sumMoviesNum = movieEntities.size();
        radapter.setMovieEntities(movieEntities);
        radapter.setCurrentType(moiveTypeName);
        radapter.notifyDataSetChanged();
        mainRv.smoothScrollToPosition(0);
        showTips();
    }

    @Override
    public void checkUpdateAppCallback(boolean isNeedUpdate, String desc) {
        if (isNeedUpdate) {
            new AlertDialog.Builder(TMovieListActivity.this, R.style.MyAlertDialogStyle)
                    .setTitle("更新提示")
                    .setPositiveButton("更新", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            moviesPresentImp.updateAppRequest();
                            progressDialog = new ProgressDialog(TMovieListActivity.this, R.style.MyAlertDialogStyle);
                            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);// 设置水平进度条
                            progressDialog.setCancelable(false);// 设置是否可以通过点击Back键取消
                            progressDialog.setCanceledOnTouchOutside(false);// 设置在点击Dialog外是否取消Dialog进度条
                            progressDialog.setTitle("更新");
                            progressDialog.setMax(100);
                            progressDialog.show();

                        }
                    })
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    })
                    .setMessage(desc)
                    .show();


        }
    }

    @Override
    public void downloadAppResult(boolean isDownloaded) {
        if (progressDialog != null) {

            progressDialog.dismiss();
        }
        if (isDownloaded) {
            ShellUtils.CommandResult commandResult = ShellUtils.execCommand("chmod 777 " + DownloadUtil.downloadPath + "/Movies.apk", true);
            Intent install = new Intent(Intent.ACTION_VIEW);
            Uri uri = Uri.parse("file:///" + DownloadUtil.downloadPath + "/" + Constant.APPID + ".apk");
            install.setDataAndType(uri, "application/vnd.android.package-archive");
            install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(install);
//            new Thread() {
//                @Override
//                public void run() {
//                    ShellUtils.CommandResult commandResult = ShellUtils.execCommand("adb install-multiple -r " + DownloadUtil.downloadPath + "/Movies.apk", true);
//                    if (commandResult.result == 255) {
//                        ShellUtils.CommandResult commandResult1 = ShellUtils.execCommand("chmod 777 " + DownloadUtil.downloadPath + "/Movies.apk", true);
//                        if (commandResult1.result == 255)
//                        ShellUtils.execCommand("am force-stop com.guobox.movies", true);
//                    }
//                }
//            }.start();

        } else {
            Toast.makeText(this, "更新失败", Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public void downloadProgress(int progress) {

        progressDialog.setProgress(progress);
    }

    @Override
    public void numTipCallback() {
        AnimationSet animationSet = new AnimationSet(true);
        TranslateAnimation translateAnimation = new TranslateAnimation(0, 200, 0, 0);
        translateAnimation.setDuration(200);
        animationSet.setFillAfter(true);
        animationSet.addAnimation(translateAnimation);
        movieNumTip.startAnimation(animationSet);
        movieNumTip.setTag(false);
    }

    @Override
    public void cateTitleTimerCallback() {
        switch (focusState) {
            case State_Cate:
                focusState = State_Movies;
                cate2Movies();
                break;
            case State_Sort:
                focusState = State_Movies;
                sort2Movies();
                NasEntity nasEntity = nasManager.getNas();
                if (nasEntity == null || TextUtils.isEmpty(nasEntity.getNasIp())) {
                    // TODO: 2017/12/11 showDialog
                } else {
                    moviesPresentImp.getMoviesRequest(catePosition, movieSort.get(sortPosition).getSortName(),nasEntity.getNasIp());
                }
                break;
        }
    }

    @Override
    public void cateSlideTimerCallback() {
        NasEntity nasEntity = nasManager.getNas();
        if (nasEntity == null || TextUtils.isEmpty(nasEntity.getNasIp())) {
            // TODO: 2017/12/11 showDialog
        } else {
            moviesPresentImp.getMoviesRequest(catePosition, movieSort.get(sortPosition).getSortName(),nasEntity.getNasIp());
        }
    }

    @Override
    public void movieFocusTimerCallback() {
//        if (moviePosition < col_num) {
//            mainRv.smoothScrollToPosition(0);
//        } else {
//            mainRv.smoothScrollToPosition(moviePosition);
//        }

        showFocus();
    }

    @Override
    public void finish() {
        if (isBack) {
            setResult(Constant.ResultLauncher);
            super.finish();
        } else {
            isBack = true;
            Toast.makeText(this, "再次按返回键退出", Toast.LENGTH_SHORT).show();
            new Thread() {
                @Override
                public void run() {
                    try {
                        sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        isBack = false;
                    }
                    isBack = false;
                }
            }.start();

        }

    }

//    @Override
//    public void onNasIpCallback(final String ip) {
//        runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                if (searchProgress != null && searchProgress.isShowing()) {
//                    searchProgress.dismiss();
//                    Toast.makeText(context, "搜索完成,已连接至"+ip, Toast.LENGTH_SHORT).show();
//                    if (searchTimer != null) {
//                        searchTimer.cancel();
//
//                    }
//                }
//            }
//        });
//    }
//
//    @Override
//    public void beforeSearchNas() {
//        if (searchProgress != null && !searchProgress.isShowing()) {
//            runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
//                    searchProgress.show();
//                    searchTimer.schedule(new TimerTask() {
//                        @Override
//                        public void run() {
//                            runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    if (searchProgress.isShowing()) {
//                                        searchProgress.dismiss();
//                                        Toast.makeText(context, "未发现设备！", Toast.LENGTH_SHORT).show();
//                                    }
//                                }
//                            });
//                        }
//                    },5000);
//                }
//            });
//        }
//    }
//
//    private void showSearchAlert() {
//        searchDialog = new MaterialDialog.Builder(this)
//                .title("提示")
//                .content("未发现NAS，是否重新搜索？")
//                .theme(Theme.DARK)
//                .buttonRippleColorRes(R.color.white)
//                .positiveText("搜索")
//                .negativeText("取消")
//                .onPositive(new MaterialDialog.SingleButtonCallback() {
//                    @Override
//                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                        nasManager.searchNas();
//                    }
//                }).positiveFocus(true).build();
//        try {
//            if (((Activity) this).hasWindowFocus()) {
//                searchDialog.show();
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//
//    @Override
//    protected void onDestroy() {
//        nasManager.unRegister();
//        super.onDestroy();
//    }
}
